//
//  Shipped.m
//  RRQS
//
//  Created by kyjun on 16/3/23.
//
//

#import "Shipped.h"
#import "TaskHeader.h"
#import "ShippedTaskCell.h"
#import "TaskFooter.h"
#import "MOrder.h"
#import "WaitTakeDetail.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "WJWaiMaiDodel.h"
#import "WaitTakeDetailViewController.h"
#import "PaotuiDetailViewController.h"

#define wmCount self.listDataMarray.count

@interface Shipped ()<ShippedTaskDelegate,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource>
@property(nonatomic,strong) NSMutableArray* arrayData;

@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSString* footerIdentifier;

@property (nonatomic, strong) WJWaiMaiDodel *waiMaiDodel; // 数据源.item
@property (nonatomic, strong) NSMutableArray *listDataMarray; // 外卖数据源
@property (nonatomic, strong) NSMutableArray *hlistDataMarray; // 跑腿数据源
@property (nonatomic, assign) NSInteger totalCountInteger; // 总数
@end

@implementation Shipped


-(instancetype)init{
    self = [super initWithCollectionViewLayout:[[UICollectionViewFlowLayout alloc]init]];
    if(self){
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.cellIdentifier = @"ShippedTaskCell";
    self.headerIdentifier = @"ShippedTaskHeader";
    self.footerIdentifier = @"ShippedTaskFooter";
    [self layoutUI];
    [self layoutConstraints];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData:) name:NotificationRefreshShippedTask object:nil];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.Identity.userInfo.isLogin){
        [self refereshDatasource];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark =====================================================  user interface layout
-(void)layoutUI{
    [self.collectionView registerClass:[ShippedTaskCell class] forCellWithReuseIdentifier:NSStringFromClass([ShippedTaskCell class])];
    [self.collectionView registerClass:[TaskHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:self.headerIdentifier];
    [self.collectionView registerClass:[TaskFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:self.footerIdentifier];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.collectionView.emptyDataSetDelegate = self;
    self.collectionView.emptyDataSetSource = self;
}

-(void)layoutConstraints{
    self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.f]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.f]];
    
}

#pragma mark =====================================================  Datasource
-(void)queryData{
    AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
    NSDictionary* arg = @{@"ince":@"get_rr_help_send_order_list",@"emp_id":self.Identity.userInfo.userID};
    [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [WMHelper outPutJsonString:responseObject];
        NSInteger flag = [[responseObject objectForKey:@"status"]integerValue];
        if(flag == 1){
#warning  TODO:当有订单从后台修改了状态 用户在刷新的时候需要刷新   这里可以作为一个通知最佳
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationHomeRefreshing object:nil];
            [self.arrayData removeAllObjects];
            
            [self.listDataMarray removeAllObjects];
            [self.hlistDataMarray removeAllObjects];
            self.waiMaiDodel = [WJWaiMaiDodel yy_modelWithDictionary:responseObject];
            [self.listDataMarray addObjectsFromArray:self.waiMaiDodel.list];
            [self.hlistDataMarray addObjectsFromArray:self.waiMaiDodel.hlist];
            
            if ([WMHelper isNULLOrnil:self.listDataMarray]) {
                if ([WMHelper isNULLOrnil:self.hlistDataMarray]) {
                    self.totalCountInteger = 0;
                }else{
                    self.totalCountInteger = self.hlistDataMarray.count;
                }
            }
            if ([WMHelper isNULLOrnil:self.hlistDataMarray]) {
                if ([WMHelper isNULLOrnil:self.listDataMarray]) {
                    self.totalCountInteger = 0;
                }else{
                    self.totalCountInteger = self.listDataMarray.count;
                }
            }
            if (![WMHelper isNULLOrnil:self.listDataMarray] && ![WMHelper isNULLOrnil:self.hlistDataMarray]) {
                self.totalCountInteger = self.listDataMarray.count + self.hlistDataMarray.count;
            }
            
//            NSArray* array = [responseObject objectForKey:@"list"];
//            if(![WMHelper isNULLOrnil:array]){
//                [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                    MOrder* item = [[MOrder alloc]initWithOrder:obj];
//                    [self.arrayData addObject:item];
//                }];
//            }
            [self.collectionView reloadData];
        }else{
            [self alertHUD:[responseObject objectForKey:@"fail"]];
        }
        [self.collectionView.mj_header endRefreshing];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [self alertHUD:@"网络异常"];
        [self.collectionView.mj_header endRefreshing];
    }];
}

-(void)refereshDatasource{
    __weak typeof(self) weakSelf = self;
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf queryData];
    }];
    [self.collectionView.mj_header beginRefreshing];
}

#pragma mark =====================================================  <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
//    MOrder* empty = self.arrayData[section];
//    if(empty){
//        return empty.arraySubOrder.count;
//    }
     return 1;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ShippedTaskCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ShippedTaskCell class]) forIndexPath:indexPath];
    
    if (![WMHelper isNULLOrnil:self.listDataMarray]) { // 如果数组不为空
        if (indexPath.section < self.listDataMarray.count) {
            cell.waiMaiDodelListitems = ((WJWaiMaiDodelList *)self.listDataMarray[indexPath.section]).items[0];
        }else{
            cell.waiMaiDodelHList = self.hlistDataMarray[indexPath.section - wmCount];
        }
    }else{// 没有跑腿 self.listDataMarray数组为空的时候
        cell.waiMaiDodelHList = self.hlistDataMarray[indexPath.section];
    }
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
//    return self.arrayData.count;
    return self.totalCountInteger;
}

// The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//    MOrder* empty = self.arrayData[indexPath.section];
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
        UICollectionReusableView  *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:self.headerIdentifier forIndexPath:indexPath];
        TaskHeader *header = (TaskHeader *) reusableView;
//         empty.status = expressStatusIng;
//        header.entity = empty;
        
        if (indexPath.section < self.listDataMarray.count) {
            header.waiMaiDodelList = self.listDataMarray[indexPath.section];
        }else{
            header.waiMaiDodelHList = self.hlistDataMarray[indexPath.section - wmCount];
        }
        return reusableView;
    }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
        UICollectionReusableView  *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:self.footerIdentifier forIndexPath:indexPath];
        TaskFooter *footer = (TaskFooter *) reusableView;
//        footer.entity = empty;
        if (indexPath.section < self.listDataMarray.count) {
            footer.waiMaiDodelList = self.listDataMarray[indexPath.section];
        }else{
            footer.waiMaiDodelHList = self.hlistDataMarray[indexPath.section - wmCount];
        }
        return reusableView;
    }
    return nil;
}

#pragma mark =====================================================  <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (![WMHelper isNULLOrnil:self.listDataMarray]) { // 如果数组不为空
        if (indexPath.section < self.listDataMarray.count) {
            WaitTakeDetailViewController *controller = [[WaitTakeDetailViewController alloc]init];
            controller.isPeiSongz = YES;
            controller.waiMaiDodelListitems = ((WJWaiMaiDodelList *)self.listDataMarray[indexPath.section]).items[0];
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            PaotuiDetailViewController *controller = [[PaotuiDetailViewController alloc]init];
            controller.isPeiSongz = YES;
            controller.waiMaiDodelHList = self.hlistDataMarray[indexPath.section - wmCount];
            [self.navigationController pushViewController:controller animated:YES];
        }
    }else{// 跑腿 self.listDataMarray数组为空的时候
        PaotuiDetailViewController *controller = [[PaotuiDetailViewController alloc]init];
        controller.isPeiSongz = YES;
        controller.waiMaiDodelHList = self.hlistDataMarray[indexPath.section];
        [self.navigationController pushViewController:controller animated:YES];
    }
}

#pragma mark =====================================================  <UICollectionViewDelegateFlowLayout>
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(SCREEN_WIDTH, 75);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(SCREEN_WIDTH, 75);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
//    MOrder* empty = self.arrayData[section];
//     MSubOrder* item = (MSubOrder*)[empty.arraySubOrder firstObject];
//    if([WMHelper isEmptyOrNULLOrnil:item.phoneAddress]){
//        return CGSizeMake(SCREEN_WIDTH, 60);
//    }
    return CGSizeMake(SCREEN_WIDTH, 90);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0.f; /// 行与行之间的间隔距离
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.f; //相邻两个 item 间距
}

#pragma mark =====================================================  <ShippedTaskDelegate>
-(void)shippedTaskConfirm:(MSubOrder *)item{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view.window];
    [self.view.window addSubview:self.HUD];
    self.HUD.delegate = self;
    self.HUD.minSize = CGSizeMake(135.f, 135.f);
    [self.HUD setLabelFont:[UIFont systemFontOfSize:14.f]];
    [self.HUD show:YES];
    AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
    NSDictionary* arg = @{@"ince":@"qs_send_food",@"emp_id":self.Identity.userInfo.userID,@"order_id":item.subOrderID};
    [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [WMHelper outPutJsonString:responseObject];
        NSInteger flag = [[responseObject objectForKey:@"status"]integerValue];
        if(flag == 1){
            [self hidHUD:@"成功" success:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationHomeRefreshing object:nil];
        }else{
            NSLog(@"%@",[responseObject objectForKey:@"fail"]);
            [self hidHUD:[responseObject objectForKey:@"fail"]];
        }
        [self queryData];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@",error.description);
        [self hidHUD:@"网络异常"];
    }];
}

#pragma mark =====================================================  DZEmptyData 协议实现
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"暂无配送中订单!" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:[UIColor grayColor]}];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return roundf(self.collectionView.frame.size.height/10.0);
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

#pragma mark =====================================================  Notification
-(void)refreshData:(NSNotification*)notification{
    [self.collectionView.mj_header beginRefreshing];
}

#pragma mark =====================================================  property package
-(NSMutableArray *)arrayData{
    if(!_arrayData){
        _arrayData = [[NSMutableArray alloc]init];
    }
    return _arrayData;
}
- (NSMutableArray *)listDataMarray
{
    if (!_listDataMarray) {
        _listDataMarray = @[].mutableCopy;
    }
    return _listDataMarray;
}
- (NSMutableArray *)hlistDataMarray
{
    if (!_hlistDataMarray) {
        _hlistDataMarray = @[].mutableCopy;
    }
    return _hlistDataMarray;
}
@end
